//useState
import React from "react";
import ReactDom from "react-dom";
// let memoizedState;
// function useReducer(reducer,initialArg,init){
//     let initialState = void 0;
//     if(typeof init!='undefined'){
//         initialState = init(initialState);
//     }else{
//         initialState = initialArg;
//     }
//     function dispatch(action){
//         memoizedState = reducer(memoizedState,action);
//         render();
//     }
//     memoizedState = memoizedState || initialArg;
//     return [memoizedState,dispatch];
// }
// function useState(initialState){ //简单版useState实现
//     memoizedState = memoizedState || initialState;
//     function setState(newState){
//         memoizedState = newState;
//         render();
//     }
//     return [memoizedState,setState];
// }
//  function useState(initialState){
//      //内部原理是用useReducder来实现
//     return useReducer((oldState,newState)=>newState, initialState);
//  }
//3.数组来实现
// let memoizedStates = [];
// let index = 0;
// function useState(initialState) {
//     memoizedStates[index] = memoizedStates[index] || initialState;
//     let currentIndex = index;
//     function setState(newState) {
//         memoizedStates[currentIndex] = newState;
//         render();
//     }
//     return [memoizedStates[index++], setState];
// }
//4.链表来实现：
let firstWorkInProgressHook = {memoizedState: null,next:null};
let workInProgressHook = firstWorkInProgressHook;
function useState(initialState) {
    let currentHook = workInProgressHook.next ? workInProgressHook.next : {memoizedState: initialState, next: null};
    function setState(newState) {
        currentHook.memoizedState = newState;
        render();
    }
    if(workInProgressHook.next){
        workInProgressHook = workInProgressHook.next;
    }else {
        workInProgressHook.next = currentHook;
        workInProgressHook = currentHook;
    }
    return [currentHook.memoizedState, setState];
}

function Counter() {
    const [name, setName] = useState('计数器');
    const [number, setNumber] = useState(0);
    return (
        <>
            <p>{name}:{number}</p>
            <button onClick={() => setName('计数器'+Date.now())}>改名称</button>
            <button onClick={() => setNumber(number + 1)}>+</button>
        </>
    );
}
function render() {
    // index=0;
    workInProgressHook = firstWorkInProgressHook;
    ReactDom.render(
        <>
            <Counter />
        </>,
        document.getElementById("root")
    );
}
render();
